/*
This file is part of IRCaBot.
IRCaBot is IRC logger with features.
Source code: https://notabug.org/acetone/ircabot.
Copyright (C) acetone, 2023.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#pragma once

#include <QHash>
#include <QMutex>
#include <QMap>

constexpr const int VOICEFLAG_TIMEOUT = 24*60*60; // 24 hours
constexpr const int VOICEFLAG_INTERVAL_TO_REMOVE_FROM_DATABASE = VOICEFLAG_TIMEOUT * 100; // 100 days
/*
 * VOICEFLAG_INTERVAL_TO_REMOVE_FROM_DATABASE needed for cases, which user reached timeout,
 * but not disconnecting from server and keep voice flag. So if user write some message to chat
 * after VOICEFLAG_TIMEOUT and he (she) existed in voiced list, timestamp of activity will succefully updated
 * else (without VOICEFLAG_INTERVAL_TO_REMOVE_FROM_DATABASE) user will be removed from database
 * after VOICEFLAG_TIMEOUT and activity timestamp not will be updated, but user still online
 * in channels with flag V and lose it after short reconnect.
 * VOICEFLAG_INTERVAL_TO_REMOVE_FROM_DATABASE needed to remove old trash from database.
 */

class VoicedList
{
public:
    VoicedList(const QString& networkName);
    VoicedList();
    void updateActivity(const QString& nickname);
    void add(const QString& nickname);
    bool del(const QString& nickname);
    void setNetworkName(const QString& networkName);
    QStringList nicks();

private:
    QMap<QString, qint64> nicksWithTimestamps();
    void serialize();
    void deserialize();

    QString path();
    QString dir();

    QString m_networkName;
    QString m_path;
    QString m_dir;

    QMutex m_timestampsMtx;
    QHash<QString, qint64> m_timestamps;

    std::atomic<qint64> m_lastSerializeTimestamp = 0;
};
